import { Options } from '../entity/Options';
import { getZipFullName, getZipName } from './parameter';
import { rm } from 'fs/promises';
import { log } from './log';
import fs from 'node:fs';
import { resolve } from 'node:path';
import extract from 'extract-zip';
import tar from 'tar';
import * as os from 'os';

export async function decompress(options: Options) {
  let zipName = getZipName(options);
  let zipFullName = getZipFullName(options);
  let cacheDir = resolve(`${options.cacheDir}`);
  let outDir = resolve(`${options.outDir}`);
  if (fs.existsSync(outDir) === true) {
    log.debug(`即将删除输出目录: '${outDir}'`);
    await rm(outDir, {force: true, recursive: true});
    log.debug('删除成功');
  }
  let extractedPath = resolve(`${cacheDir}/${zipName}`);
  if (fs.existsSync(extractedPath) === true) {
    log.debug(`即将删除缓存中解压缩后的目录: '${extractedPath}'`);
    await rm(extractedPath, {force: true, recursive: true});
    log.debug('删除成功');
  }
  let zipPath = resolve(`${options.cacheDir}/${zipFullName}`);
  log.debug(`即将解压安装包, 压缩包位置: '${zipPath}', 目标位置: '${cacheDir}'`);
  if (options.platform === 'linux') {
    await tar.extract({file: zipPath, C: cacheDir});
  } else {
    if ('darwin' !== os.platform() && 'osx' === options.platform) {
      log.error(`您正在非osx系统中打包osx应用，可能会出现错误，强烈建议您使用osx系统打包。`);
    }
    await extract(zipPath, {dir: cacheDir});
  }
  log.debug('解压成功');
}
